<?php

namespace App\ApiFrontend;

use App\Domains\UserDomain;
use App\Http\Controllers\ApiBaseController;
use App\Models\UserModel;
use Hash;
use Illuminate\Support\Facades\DB;

/**
 *  登陆
 */
class LoginRegister extends ApiBaseController
{

  /**
   * 参数检查
   */
  protected function check(): void
  {
    $type = request('type') ?? 'username';
    $ruleArr = [];
    if ($type == 'openid') {//微信
      $ruleArr['openid'] = 'required';
    } elseif ($type == 'openidDing') {//钉钉
      $ruleArr['openid'] = 'required';
    } else {
      $ruleArr['username'] = 'required';
      $ruleArr['password'] = 'required';
    }
    try {
      request()->validate($ruleArr);
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $moduleName = 'exam';
    $type = request('type') ?? 'username';
    $openid = \request('openid');
    $username = \request('username');
    $password = \request('password');
    try {
      //查询账号
      if ($type == 'openid') {
        $userId = DB::table('user')->where('openid', $openid)->value('userId');
      } elseif ($type == 'openidDing') {
        $userId = DB::table('user')->where('openidDing', $openid)->value('userId');
      } elseif ($type == 'username') {
        $userId = DB::table('user')->where('username', $username)->orWhere('phone', $username)->value('userId');
      }
      //无账号自动注册
      if (empty($userId)) {
        $userDomain = new UserDomain();
        $memberData = [
          'username' => $username ?? $userDomain->createUniqueUsername($moduleName),
          'module' => ($moduleName),
        ];
        if ($type == 'openid') {
          $memberData['openid'] = $openid;
          $memberData['password'] = $openid;
        } elseif ($type == 'openidDing') {
          $memberData['phone'] = request('phone') ?? '';
          $memberData['openidDing'] = $openid;
          $memberData['realname'] = request('name') ?? '';
          $memberData['password'] = $openid;
        } elseif ($type == 'username') {
          $memberData['password'] = $password ?? '123456';
        }
        $result = $userDomain->addMember($memberData);
        if ($result['status'] == 0) {
          throw new \Exception("添加失败," . $result['message']);
        }
        $userId = $result['data']['userId'];
      }

      $user = UserModel::find($userId);
      if ($user->status <= 0) {
        throw new \Exception("账号状态不正确, 无法登录");
      }
      if ($type == 'username' && !Hash::check(\request('password'), $user->password)) {
        throw new \Exception("用户密码错误");
      }
      //删除之前token
      $user->destroyAuthTokens();
      $this->result['data'] = [
        'token' => $user->getAuthToken(),
      ];

      //登录日志
      // $requestLog = [
      //     "ip" => request()->ip(),
      //     "userAgent" => request()->header("user-agent"),
      // ];
      // AdminLoginLogJob::dispatch($user, (object)$requestLog);//->onQueue('log');
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }
  }
}
